package com.sarnath.sardoop.modules.sys.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.sarnath.sardoop.modules.hbase.entity.QueryCondition;
import com.sarnath.sardoop.modules.hbase.service.HbaseQueryService;
import com.sarnath.sardoop.modules.sys.entity.User;

/**
 * 用户信息管理
 * @author yingc
 *
 */
@Service
@Lazy(false)
public class UserUtils {
	private static Logger logger=LoggerFactory.getLogger(UserUtils.class);
	private static Map<String, User> users=new HashMap<>();
	@Resource
	private HbaseQueryService hbaseQuery;
	
	public static User getUser(){
	    String userId=(String)getRequestAttr("userId");
	    User user=userId==null?null:users.get(userId);
	    if(user==null) throw new RuntimeException("not login");
		return user;
	}
	
	public static String getNameSpace(){
		return getUser().getNamespace();
	}
	
	public static HttpServletRequest getRequest(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
	    HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();
	    return request;
	}
	
	public static void setRequestAttr(String key,Object value){
		getRequest().setAttribute(key, value);
	}
	
	public static Object getRequestAttr(String key){
		Object obj=getRequest().getParameter(key);
		if(obj==null){
			obj=getRequest().getAttribute(key);
		}
		return obj;
	}
	
	@Scheduled(fixedDelay=3600000)
	public void initUsers(){
		try {
			Map<String, User> tmpUsers=new HashMap<>();
			QueryCondition condition=new QueryCondition(User.class,"sys:user");
			List<Object> l=hbaseQuery.query(condition);
			for(Object u:l){
				tmpUsers.put(((User)u).getId(), (User)u);
			}
			users=tmpUsers;
			logger.info("用户刷新：{}",l.size());
		} catch (Exception e) {
			logger.error("用户列表刷新失败",e);
		}
	}
}
